﻿using System;
using System.Linq.Expressions;

namespace WebPic.Sample.Comum {
    /// <summary>
    /// Provides a default implementation of the <see cref="ISpecification{T}"/> interface.
    /// </summary>
    /// <remarks>
    /// The <see cref="Specification{T}"/> implements Composite Specification pattern by overloading
    /// the & and | (And, Or in VB.Net) operators to allow composing multiple specifications together.
    /// </remarks>
    public class Specification<T> : ISpecification<T> {
        #region fields
        private readonly Expression<Func<T, bool>> _predicate;
        #endregion

        #region .ctor
        /// <summary>
        /// Default Constructor.
        /// Creates a new instance of the <see cref="Specification{T}"/> instnace with the
        /// provided predicate expression.
        /// </summary>
        /// <param name="predicate">A predicate that can be used to check entities that
        /// satisfy the specification.</param>
        public Specification(Expression<Func<T, bool>> predicate) {
            _predicate = predicate;
        }
        #endregion

        #region Implementation of ISpecification<T>
        /// <summary>
        /// Gets the expression that encapsulates the criteria of the specification.
        /// </summary>
        public Expression<Func<T, bool>> Predicate {
            get { return _predicate; }
        }

        /// <summary>
        /// Evaluates the specification against an entity of <typeparamref name="T"/>.
        /// </summary>
        /// <param name="entity">The <typeparamref name="T"/> instance to evaulate the specificaton
        /// against.</param>
        /// <returns>Should return true if the specification was satisfied by the entity, else false. </returns>
        public bool IsSatisfiedBy(T entity) {
            return _predicate.Compile().Invoke(entity);
        }
        #endregion

        public static Specification<T> operator &(Specification<T> leftSide, Specification<T> rightSide) {
            return new Specification<T>(leftSide.Predicate.And(rightSide.Predicate));
        }

        public static Specification<T> operator |(Specification<T> leftSide, Specification<T> rightSide) {
            return new Specification<T>(leftSide.Predicate.Or(rightSide.Predicate));
        }
    }
}